from django.db import models

from django.core.files.base import ContentFile
from PIL import Image as PilImage
import io
from django_ckeditor_5.fields import CKEditor5Field


# Create your models here.

class Category(models.Model):
    title = models.CharField(verbose_name="分类", max_length=20, unique=True)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = "分类"
        verbose_name_plural = "分类"


class Theme(models.Model):
    title = models.CharField(verbose_name="主题", max_length=20, unique=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='themes', verbose_name="所属分类",default=1)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = "主题"
        verbose_name_plural = "主题"


class ThemeTwo(models.Model):
    title = models.CharField(verbose_name="排行榜", max_length=20, unique=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='themes_two', verbose_name="所属分类",default=2)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = "排行榜"
        verbose_name_plural = "排行榜"




class Tag(models.Model):
    title = models.CharField(verbose_name="标签", max_length=20, unique=True)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = "标签"
        verbose_name_plural = "标签"


class Book(models.Model):
    title = models.CharField(verbose_name="书名", max_length=20, unique=True)
    auther = models.CharField(verbose_name="作者",max_length=20,null=False)
    image = models.ImageField(verbose_name="图片", upload_to='image')
    thumb_image = models.ImageField(verbose_name="缩略图", upload_to='thumb_image', blank=True, null=True)
    preview_image = models.ImageField(verbose_name="预览图", upload_to='preview_image', blank=True, null=True)
    description = models.TextField(verbose_name="简介", blank=True)
    views = models.IntegerField(verbose_name="下载量", default=0)
    favorite_count = models.IntegerField(verbose_name="下载量",default=0)
    category = models.ForeignKey(verbose_name="分类", to=Category, on_delete=models.CASCADE,default=1)
    theme = models.ManyToManyField(verbose_name="主题", to=Theme)
    themeTwo = models.ManyToManyField(verbose_name="排行榜", to=ThemeTwo)
    vip_require = models.BooleanField(verbose_name="是否需要vip", default=False)

    def save(self, *args, **kwargs):
        # 调用父类的保存方法以保存原始图像
        if self.image:
            img = PilImage.open(self.image)
            img.thumbnail((300, 300))  # 设置预览图的大小

            # 转换为 RGB 模式
            if img.mode != 'RGB':
                img = img.convert('RGB')

            thumb_io = io.BytesIO()
            img.save(thumb_io, format='JPEG')  # 保存为 JPEG 格式
            thumb_file = ContentFile(thumb_io.getvalue(), name=f'preview_{self.image.name}')
            self.thumb_image.save(thumb_file.name, thumb_file, save=False)

        if self.image:
            pre_img = PilImage.open(self.image)
            pre_img.thumbnail((800, 800))  # 设置预览图的大小

            # 转换为 RGB 模式
            if pre_img.mode != 'RGB':
                pre_img = pre_img.convert('RGB')

            pre_io = io.BytesIO()
            pre_img.save(pre_io, format='JPEG')  # 保存为 JPEG 格式
            pre_file = ContentFile(pre_io.getvalue(), name=f'preview_{self.image.name}')
            self.preview_image.save(pre_file.name, pre_file, save=False)

        # 再次保存模型以存储缩略图和预览图路径
        super().save(*args, **kwargs)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = "书籍"
        verbose_name_plural = "书籍"


class Article(models.Model):
    book = models.ForeignKey(verbose_name="所属书籍", to=Book, on_delete=models.CASCADE, default=1)
    title = models.CharField('文章标题', max_length=200)
    text = CKEditor5Field('正文', config_name='default')

    def __str__(self):
        return self.title


    class Meta:
        verbose_name = "文章"
        verbose_name_plural = "文章"
